package cn.zymall.massage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.zymall.massage.mapper.ShortMessageMapper;
import cn.zymall.common.model.ShortMessage;
import cn.zymall.massage.service.ShortMessageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (ShortMessage)表服务实现类
 *
 * @author makejava
 * @since 2020-08-24 10:08:11
 */
@Service("shortMessageService")
public class ShortMessageServiceImpl extends ServiceImpl<ShortMessageMapper, ShortMessage> implements ShortMessageService {
	@Value("${aliyunMsg.msgRegionId}")
	private String msgRegionId;

	@Value("${aliyunMsg.accessKeyId}")
	private String accessKeyId;

	@Value("${aliyunMsg.secet}")
	private String secet;

	@Override
	public boolean save(ShortMessage shortMessage) {
		DefaultProfile profile = DefaultProfile.getProfile( msgRegionId, accessKeyId,secet);
		IAcsClient client = new DefaultAcsClient(profile);
		CommonRequest request = new CommonRequest();
		request.setSysMethod(MethodType.POST);
		request.setSysDomain("dysmsapi.aliyuncs.com");
		request.setSysVersion("2017-05-25");
		request.setSysAction("AddSmsTemplate");
		request.putQueryParameter("RegionId", "cn-hangzhou");
		request.putQueryParameter("TemplateType", String.valueOf(shortMessage.getTemplateType()));
		request.putQueryParameter("TemplateName", shortMessage.getTemplateName());
		request.putQueryParameter("TemplateContent", shortMessage.getTemplateContent());
		request.putQueryParameter("Remark", shortMessage.getTempldateExplain());
		try {
			if(shortMessage.getTemplateParam()!=null&&shortMessage.getTemplateContent().indexOf(shortMessage.getTemplateParam())==-1){
				return false;
			}
			CommonResponse response = client.getCommonResponse(request);
			String data = response.getData();
			Map dataMap = (Map) JSONObject.parseObject(data);
			String templateCode = (String)dataMap.get("TemplateCode");
			String code = (String) dataMap.get("Code");
			if(code.equals("isv.SMS_SIGNATURE_SCENE_ILLEGAL")){
				return false;
			}else if(code.equals("isv.SMS_SIGN_ILLEGAL")){
				return false;
			}else if(code.equals("OK")){
				shortMessage.setTemplateStatus((byte)0);
				shortMessage.setTemplateCode(templateCode);
				return super.save(shortMessage);
			}
		} catch (ServerException e) {
			e.printStackTrace();
			return false;
		} catch (ClientException e) {
			e.printStackTrace();
			return false;
		}
		return false;
	}

	@Override
	public List<ShortMessage> list() {

		return super.list(new QueryWrapper<ShortMessage>().orderByDesc("TEMPLATE_UPDATE_TIME"));
	}

	@Override
	@Scheduled(fixedDelay = 1000*60*60)
	public void run() {
		List<ShortMessage> templateUpdateTime = list();
		if (templateUpdateTime.isEmpty()) {
			return;
		} else {
			List<ShortMessage> messages = templateUpdateTime.stream().filter(template -> template.getTemplateStatus() == 0).collect(Collectors.toList());
			messages.forEach(e -> {
				DefaultProfile profile = DefaultProfile.getProfile(msgRegionId, accessKeyId, secet);
				IAcsClient client = new DefaultAcsClient(profile);
				CommonRequest request = new CommonRequest();
				request.setSysMethod(MethodType.POST);
				request.setSysDomain("dysmsapi.aliyuncs.com");
				request.setSysVersion("2017-05-25");
				request.setSysAction("QuerySmsTemplate");
				request.putQueryParameter("RegionId", "cn-hangzhou");
				request.putQueryParameter("TemplateCode", e.getTemplateCode());
				try {
					CommonResponse response = client.getCommonResponse(request);
					System.out.println("---" + response.getData());
					String data = response.getData();
					System.out.println("data::"+data);
					Map dataMap = (Map) JSONObject.parseObject(data);
					Integer code = (Integer) dataMap.get("TemplateStatus");
					ShortMessage shortMessage=e;
					if(code==1){
						shortMessage.setTemplateStatus((byte)1);
						updateById(shortMessage);
					}else if(code==2){
						shortMessage.setTemplateStatus((byte)4);
						updateById(shortMessage);
					}
				} catch (ClientException clientException) {
					clientException.printStackTrace();
				}
			});
		}
	}
}
